package com.dzsw.dp.corp.chain.general;


import com.dzsw.dp.corp.chain.handler.GeneralHandler;
import com.dzsw.dp.corp.chain.handler.GeneralHandlerRequest;
import com.dzsw.dp.corp.chain.handler.GeneralHandlerResponse;

import java.util.stream.Stream;

public abstract class GeneralChain {

    private GeneralHandler[] handlerChainList;

    /**
     * 初始化任务处理链
     *
     * @param handlers 按handler处理顺序传参
     */
    protected void initChain(GeneralHandler...handlers){
        handlerChainList = Stream.of(handlers).toArray(GeneralHandler[]::new);

        // 创建正向链表
        int handlerLength = handlerChainList.length;
        for (int i =0; i < handlerLength; i++){
            if (i+1 < handlerLength){
                handlerChainList[i].setNext(handlerChainList[i+1]);
            }
        }

        // 创建反向链表
        for(int i =handlerLength -1; i >0; i--){
            handlerChainList[i].setPre(handlerChainList[i - 1]);
        }
    }

    /**
     * 处理链调用入库
     *
     * @param request
     * @param response
     */
    protected void requestChain(GeneralHandlerRequest request, GeneralHandlerResponse response){
        handlerChainList[0].startHandler(request, response);
    }

}
